<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#fff">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">




  
  
    
      
    
    
      
    
  <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
  <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "b3c7d22e"
    });
  daovoice('update');
  </script>








  <meta name="baidu-site-verification" content="true" />







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="mask-icon" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1" color="#fff">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"perspectiveLeftIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"perspectiveLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键字","hits_empty":"没有找到与 ${query} 相关的内容","hits_stats":"${hits}条相关记录，共耗时${time} ms"}
    }
  };
</script>


  



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://yfzhou.coding.me/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>

  <meta name="description" content="MongoDB学习笔记">
<meta name="keywords" content="MongoDB,NoSQL">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）">
<meta property="og:url" content="https://yfzhou.coding.me/2018/11/06/MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）/index.html">
<meta property="og:site_name" content="Felix">
<meta property="og:description" content="MongoDB学习笔记">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-f4af7e3ac87f58db.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/742/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-62123818bf6065c3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/742/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-306219905f1cb2fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/858/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-7b32e19155165d6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/743/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-2faceb92a959341b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/570/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-9b33ceb394bb84f4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/744/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-27e67e57e7f046b4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/741/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-4b259a703b51d8c8.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/743/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-a421f1c25b2a04ef.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/745/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-8a6d608934b86d65.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/740/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-e9d69c889fe53ec1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/500/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-d9664d2b1c06bbae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-56bf2bffa5a97ef4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/973/format/webp">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/5832745-c423bb3678ba4d12.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/661/format/webp">
<meta property="og:updated_time" content="2019-04-17T08:59:25.072Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）">
<meta name="twitter:description" content="MongoDB学习笔记">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/5832745-f4af7e3ac87f58db.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/742/format/webp">



  <link rel="alternate" href="/atom.xml" title="Felix" type="application/atom+xml" />




  <link rel="canonical" href="https://yfzhou.coding.me/2018/11/06/MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等） | Felix</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Felix</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">Viva La Vida</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />TopX</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="输入关键字搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yfzhou.coding.me/2018/11/06/MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Felix">
      <meta itemprop="description" content="周宇峰的博客">
      <meta itemprop="image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Felix">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-11-06 14:17:33" itemprop="dateCreated datePublished" datetime="2018-11-06T14:17:33+08:00">2018-11-06</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-17 16:59:25" itemprop="dateModified" datetime="2019-04-17T16:59:25+08:00">2019-04-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/MongoDB/" itemprop="url" rel="index"><span itemprop="name">MongoDB</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/11/06/MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）/" class="leancloud_visitors" data-flag-title="MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-edit"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">26k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">32 分钟</span>
              
            </div>
          

          
              <div class="post-description">MongoDB学习笔记</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><span></span></p>
<a id="more"></a>
<h1 id="MongoDB-简介"><a href="#MongoDB-简介" class="headerlink" title="MongoDB - 简介"></a>MongoDB - 简介</h1><div class="note info"><p>官网：<a href="https://www.mongodb.com/" target="_blank" rel="noopener">https://www.mongodb.com</a></p></div>

<ul>
<li>MongoDB 是一个基于分布式文件存储的数据库，由 C++ 语言编写，旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。</li>
<li>MongoDB 是一个介于关系数据库和非关系数据库之间的产品，是非关系数据库当中功能最丰富，最像关系数据库的。</li>
<li>MongoDB 将数据存储在类似JSON的灵活文档中，这意味着字段可能因文档而异，并且数据结构可能会随时间而变化</li>
<li>文档模型映射到应用程序代码中的对象，使数据易于使用</li>
<li>即席查询，索引和实时聚合提供了访问和分析数据的强大方法</li>
<li>MongoDB是一个分布式数据库，因此内置了高可用性，水平扩展和地理分布，并且易于使用</li>
<li>MongoDB是免费的开源软件。2018年10月16日之前发布的版本根据AGPL发布。2018年10月16日之后发布的所有版本（包括先前版本的修补程序）都在<a href="https://www.mongodb.com/licensing/server-side-public-license" target="_blank" rel="noopener">服务器端公共许可证（SSPL）v1下发布</a>。</li>
</ul>
<h1 id="MongoDB-安装及运行"><a href="#MongoDB-安装及运行" class="headerlink" title="MongoDB - 安装及运行"></a>MongoDB - 安装及运行</h1><ol>
<li><p>下载<br>我下载的是4.0.3版本<br><a href="https://www.mongodb.com/download-center/community" target="_blank" rel="noopener">https://www.mongodb.com/download-center#community</a></p>
</li>
<li><p>创建数据目录<br>MongoDB 将数据目录存储在 db 目录下，需手动创建。<br> <code>D:\MongoDB\data\db</code></p>
</li>
<li><p>运行 MongoDB 服务器<br>为了从命令提示符下运行MongoDB服务器，你必须从<code>MongoDB\bin</code>目录中执行<code>mongod.exe</code>文件，不要关闭服务。<code>ctrl + c</code>关闭。<br><code>mongod.exe --dbpath D:\MongoDB\data\db</code></p>
</li>
<li><p>MongoDB 后台管理<br>运行 mongo.exe<br>MongoDB Shell是MongoDB自带的交互式Javascript shell,用来对MongoDB进行操作和管理的交互式环境。</p>
</li>
<li><p>将 MongoDB 服务器作为 Windows 服务运行<br>添加系统环境 path <code>D:\MongoDB\Server\3.4\bin</code><br>检测：cmd 中输入 <code>mongod --help</code><br>新建文件：<code>D:\MongoDB\logs\logs.log</code><br>将 MongoDB 服务器作为 Windows 服务随 Windows 启动而开启：<br>mongod.exe –logpath “D:\MongoDB\logs\logs.log” –logappend –dbpath “D:\MongoDB\data” –directoryperdb –serviceName MongoDB –install</p>
</li>
</ol>
<p>开启 MongoDB 服务：<code>net start MongoDB</code><br>停止 MongoDB 服务：<code>net stop MongoDB</code><br>删除 MongoDB 服务：<code>sc delete MongoDB</code></p>
<p>接下来就可以在 cmd 中运行 <code>D:\MongoDB\Server\3.4\bin</code> 里面的 <code>*.exe</code> 程序了</p>
<ul>
<li>shell 控制台 <code>mongo</code></li>
<li>数据库的还原 <code>mongorestore</code></li>
<li>备份 <code>mongodump</code></li>
</ul>
<ol start="6">
<li>mongodb 启动的参数</li>
</ol>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-f4af7e3ac87f58db.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/742/format/webp" alt=""></p>
<h1 id="mongoDB-主要特点"><a href="#mongoDB-主要特点" class="headerlink" title="mongoDB - 主要特点"></a>mongoDB - 主要特点</h1><ul>
<li>MongoDB安装简单。</li>
<li>MongoDB的提供了一个面向文档存储，没有表结构的概念，每天记录可以有完全不同的结构，操作起来比较简单和容易。</li>
<li>完全的索引支持（单键索引、数组索引、全文索引、地理位置索引 等）</li>
<li>你可以通过本地或者网络创建数据镜像，这使得MongoDB有更强的扩展性。</li>
<li>如果负载的增加（需要更多的存储空间和更强的处理能力） ，它可以分布在计算机网络中的其他节点上这就是所谓的分片。</li>
<li>Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记，可轻易查询文档中内嵌的对象及数组。</li>
<li>MongoDb 使用update()命令可以实现替换完成的文档（数据）或者一些指定的数据字段 。</li>
<li>Mongodb中的Map/reduce主要是用来对数据进行批量处理和聚合操作。</li>
<li>Map和Reduce。Map函数调用emit(key,value)遍历集合中所有的记录，将key与value传给Reduce函数进行处理。</li>
<li>Map函数和Reduce函数是使用Javascript编写的，并可以通过db.runCommand或mapreduce命令来执行MapReduce操作。</li>
<li>GridFS是MongoDB中的一个内置功能，可以用于存放大量小文件。</li>
<li>MongoDB允许在服务端执行脚本，可以用Javascript编写某个函数，直接在服务端执行，也可以把函数的定义存储在服务端，下次直接调用即可。</li>
<li>MongoDB 支持多种编程语言:C C++ C# .NET Erlang Haskell Java JavaScript Lisp node.JS Perl PHP Python Ruby Scala 等</li>
</ul>
<h1 id="mongoDB-工具"><a href="#mongoDB-工具" class="headerlink" title="mongoDB - 工具"></a>mongoDB - 工具</h1><p>监控</p>
<ul>
<li>Munin：网络和系统监控工具</li>
<li>Gangila：网络和系统监控工具</li>
<li>Cacti：用于查看CPU负载, 网络带宽利用率，它也提供了一个应用于监控 MongoDB 的插件。</li>
</ul>
<p>GUI</p>
<ul>
<li>Robomongo（Robo 3T）</li>
<li>Fang of Mongo – 网页式，由Django和jQuery所构成。</li>
<li>Futon4Mongo – 一个CouchDB Futon web的mongodb山寨版。</li>
<li>Mongo3 – Ruby写成。</li>
<li>MongoHub – 适用于OSX的应用程序。</li>
<li>Opricot – 一个基于浏览器的MongoDB控制台, 由PHP撰写而成。</li>
<li>Database Master — Windows的mongodb管理工具</li>
<li>RockMongo — 最好的PHP语言的MongoDB管理工具，轻量级, 支持多国语言.</li>
<li>Navicat Premium 12 — 个人最喜欢用的一款数据库管理工具，12版本支持了mongodb,支持mysql,oracle,sql server等多种数据库(<a href="/2018/11/06/Navicat-Premium-12-1-8-0安装与激活/">破解方法点击这里</a>)<h1 id="mongoDB-三大重要概念"><a href="#mongoDB-三大重要概念" class="headerlink" title="mongoDB - 三大重要概念"></a>mongoDB - 三大重要概念</h1></li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-62123818bf6065c3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/742/format/webp" alt="" title="该表将帮助您更容易理解Mongo中的一些概念"></p>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-306219905f1cb2fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/858/format/webp" alt=""></p>
<h2 id="1-database-数据库"><a href="#1-database-数据库" class="headerlink" title="1. database 数据库"></a>1. database 数据库</h2><p>多个集合逻辑上组织在一起，就是数据库。</p>
<p>数据库命名规范：</p>
<ul>
<li>不能是空字符串（””)。</li>
<li>不得含有’ ‘（空格)、.、$、/、\和\0 (空字符)。</li>
<li>应全部小写。</li>
<li>最多64字节。</li>
</ul>
<p>有一些数据库名是保留的，可以直接访问这些有特殊作用的数据库。</p>
<ul>
<li>admin： 从权限的角度来看，这是”root”数据库。要是将一个用户添加到这个数据库，这个用户自动继承所有数据库的权限。一些特定的服务器端命令也只能从这个数据库运行，比如列出所有的数据库或者关闭服务器。</li>
<li>local: 这个数据永远不会被复制，可以用来存储限于本地单台服务器的任意集合</li>
<li>config: 当Mongo用于分片设置时，config数据库在内部使用，用于保存分片的相关信息。</li>
</ul>
<h2 id="2-collection-集合"><a href="#2-collection-集合" class="headerlink" title="2. collection 集合"></a>2. collection 集合</h2><p>多个文档组成一个集合，相当于关系数据库的表。</p>
<p>所有存储在集合中的数据都是 BSON 格式，BSON 是类 JSON 的一种二进制形式的存储格式，简称 Binary JSON。</p>
<p>集合名命名规范：</p>
<ul>
<li>集合名不能是空字符串””。</li>
<li>集合名不能含有\0字符（空字符)，这个字符表示集合名的结尾。</li>
<li>集合名不能以”system.”开头，这是为系统集合保留的前缀。</li>
<li>用户创建的集合名字不能含有保留字符。有些驱动程序的确支持在集合名里面包含，这是因为某些系统生成的集合中包含该字符。除非你要访问这种系统创建的集合，否则千万不要在名字里出现$。</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-7b32e19155165d6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/743/format/webp" alt=""></p>
<h2 id="3-document-文档"><a href="#3-document-文档" class="headerlink" title="3. document 文档"></a>3. document 文档</h2><p>MongoDB 将数据存储为一个文档，数据结构由键值对组成。</p>
<p>MongoDB 文档是一组键值对(即BSON，二进制的 JSON)，类似于 JSON 对象。字段值可以包含其他文档，数组及文档数组。</p>
<p>文档键命名规范：</p>
<ul>
<li>键不能含有\0 (空字符)。这个字符用来表示键的结尾。</li>
<li>.和$有特别的意义，只有在特定环境下才能使用。</li>
<li>以下划线”_”开头的键是保留的(不是严格要求的)。</li>
</ul>
<p>需要注意的是：</p>
<ul>
<li>文档中的键值对是有序的。</li>
<li>文档中的值不仅可以是在双引号里面的字符串，还可以是其他几种数据类型（甚至可以是整个嵌入的文档)。</li>
<li>MongoDB区分类型和大小写。</li>
<li>MongoDB的文档不能有重复的键。</li>
<li>文档的键是字符串。除了少数例外情况，键可以使用任意UTF-8字符。</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-2faceb92a959341b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/570/format/webp" alt=""></p>
<h1 id="MongoDB-数据类型"><a href="#MongoDB-数据类型" class="headerlink" title="MongoDB - 数据类型"></a>MongoDB - 数据类型</h1><p>ObjectId：主键，一种特殊而且非常重要的类型，每个文档都会默认配置这个属性，属性名为_id，除非自己定义，方可覆盖</p>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-9b33ceb394bb84f4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/744/format/webp" alt=""></p>
<h1 id="MongoDB-常见操作"><a href="#MongoDB-常见操作" class="headerlink" title="MongoDB - 常见操作"></a>MongoDB - 常见操作</h1><h2 id="查看当前数据库"><a href="#查看当前数据库" class="headerlink" title="查看当前数据库"></a>查看当前数据库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db</span><br></pre></td></tr></table></figure>
<h2 id="查看所有数据库"><a href="#查看所有数据库" class="headerlink" title="查看所有数据库"></a>查看所有数据库</h2><p>没有数据的数据库不予显示</p>
<p>MongoDB 中默认的数据库为 test，如果你没有创建新的数据库，集合将存放在 test 数据库中。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show dbs</span><br></pre></td></tr></table></figure></p>
<h2 id="连接到指定的数据库"><a href="#连接到指定的数据库" class="headerlink" title="连接到指定的数据库"></a>连接到指定的数据库</h2><p>如果数据库不存在，则创建数据库，否则切换到指定数据库。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">use db_name</span><br></pre></td></tr></table></figure></p>
<h2 id="查看服务器状态"><a href="#查看服务器状态" class="headerlink" title="查看服务器状态"></a>查看服务器状态</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.serverStatus()</span><br></pre></td></tr></table></figure>
<h2 id="查看数据库统计信息"><a href="#查看数据库统计信息" class="headerlink" title="查看数据库统计信息"></a>查看数据库统计信息</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.stats()</span><br></pre></td></tr></table></figure>
<h2 id="删除数据库"><a href="#删除数据库" class="headerlink" title="删除数据库"></a>删除数据库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.dropDatabase()</span><br></pre></td></tr></table></figure>
<h2 id="查看数据库中所有集合"><a href="#查看数据库中所有集合" class="headerlink" title="查看数据库中所有集合"></a>查看数据库中所有集合</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">show tables</span><br><span class="line"><span class="comment">//或</span></span><br><span class="line">show collections</span><br></pre></td></tr></table></figure>
<h2 id="清空集合"><a href="#清空集合" class="headerlink" title="清空集合"></a>清空集合</h2><p>删除里面的文档，但集合还在<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.remove(&#123;&#125;)</span><br></pre></td></tr></table></figure></p>
<p>删除集合<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.drop()</span><br></pre></td></tr></table></figure></p>
<p>查看集合详细信息</p>
<p>MongoDB 的3.0后的版本分了三种模式 queryPlanner、executionStats、allPlansExecution<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find(&#123;key:value&#125;).explain(&quot;allPlansExecution&quot;)</span><br></pre></td></tr></table></figure></p>
<h1 id="MongoDB-增删改查"><a href="#MongoDB-增删改查" class="headerlink" title="MongoDB - 增删改查"></a>MongoDB - 增删改查</h1><h2 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h2><p>MongoDB 使用 insert() 或 save() 方法向集合中插入文档：<br>如果该集合不在该数据库中， MongoDB 会<code>自动创建该集合并插入文档</code>。</p>
<p>insert() 或 save() 方法都可以向collection里插入数据，两者区别：</p>
<ul>
<li>如果不指定 _id 字段，<strong>save() 方法</strong>类似于 insert() 方法。如果指定 _id 字段，则会更新该 _id 的数据。</li>
<li>使用save函数，如果原来的对象不存在，那他们都可以向collection里插入数据，如果已经存在，save会调用update更新里面的记录，而insert则会忽略操作</li>
<li>insert可以一次性插入一个列表，而不用遍历，效率高， save则需要遍历列表，一个个插入。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.insert(document)</span><br><span class="line">db.col_name.save(document)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>插入一个文档到 col 集合中：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">db.col_1.insert(&#123;</span><br><span class="line">    title: &apos;MongoDB 教程&apos;,</span><br><span class="line">    description: &apos;MongoDB 是一个 Nosql 数据库&apos;,</span><br><span class="line">    by: &apos;菜鸟教程&apos;,</span><br><span class="line">    url: &apos;http://www.runoob.com&apos;,</span><br><span class="line">    tags: [&apos;mongodb&apos;, &apos;database&apos;, &apos;NoSQL&apos;],</span><br><span class="line">    likes: 100</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>也可以将文档数据定义为一个变量，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">document = (&#123;</span><br><span class="line">    title: &apos;MongoDB 教程&apos;,</span><br><span class="line">    description: &apos;MongoDB 是一个 Nosql 数据库&apos;,</span><br><span class="line">    by: &apos;菜鸟教程&apos;,</span><br><span class="line">    url: &apos;http://www.runoob.com&apos;,</span><br><span class="line">    tags: [&apos;mongodb&apos;, &apos;database&apos;, &apos;NoSQL&apos;],</span><br><span class="line">    likes: 101</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">db.col_2.insert(document)</span><br></pre></td></tr></table></figure></p>
<h2 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h2><p>remove() 函数是用来删除集合中的数据</p>
<p>在执行 remove() 函数前先执行 find() 命令来判断执行的条件是否正确，这是一个比较好的习惯。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.remove(</span><br><span class="line">   &lt;query&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     justOne: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure></p>
<ul>
<li>query :（可选）删除的文档的条件。</li>
<li>justOne : （可选）如果设为 true 或 1，则只删除一个文档。</li>
<li>writeConcern :（可选）抛出异常的级别。</li>
</ul>
<p>删除集合中所有文档<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col.remove(&#123;&#125;)</span><br></pre></td></tr></table></figure></p>
<p>移除 col_1 集合中 title 为 MongoDB save 的文档，只删除第一条找到的记录<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_1.remove(&#123;&apos;title&apos;:&apos;MongoDB save&apos;&#125;, 1)</span><br></pre></td></tr></table></figure></p>
<h2 id="更新"><a href="#更新" class="headerlink" title="更新"></a>更新</h2><p>MongoDB 使用 update() 和 save() 方法来更新集合中的文档</p>
<p><strong>update() 方法</strong>用于更新已存在的文档<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.update(</span><br><span class="line">   &lt;query&gt;,</span><br><span class="line">   &lt;update&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     upsert: &lt;boolean&gt;,</span><br><span class="line">     multi: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure></p>
<ul>
<li>query : update 的查询条件，类似sql update查询内where后面的。</li>
<li>update : update的对象和一些更新的操作符（如$,$inc…）等，也可以理解为sql update查询内set后面的</li>
<li>upsert : 可选，这个参数的意思是，如果不存在 update 的记录，是否插入记录，true 为插入，默认是 false，不插入。</li>
<li>multi : 可选，mongodb 默认是false,只更新找到的第一条记录，如果这个参数为true,就把按条件查出来多条记录全部更新。</li>
<li>writeConcern :可选，抛出异常的级别。</li>
</ul>
<p>通过 update() 方法来更新 col_1 集合中的 title</p>
<p>$set 操作符为部分更新操作符，只更新 $set 之后的数据，而不是覆盖之前的数据<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_1.update(&#123; &apos;title&apos;: &apos;MongoDB 教程&apos; &#125;, &#123; $set: &#123; &apos;title&apos;: &apos;MongoDB&apos; &#125; &#125;)</span><br></pre></td></tr></table></figure></p>
<p>以上语句只会修改第一条发现的文档，如果要修改多条相同的文档，则需要设置 multi 参数为 true。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_1.update(&#123; &apos;title&apos;: &apos;MongoDB 教程&apos; &#125;, &#123; $set: &#123; &apos;title&apos;: &apos;MongoDB&apos; &#125; &#125;, &#123; multi: true &#125;)</span><br></pre></td></tr></table></figure></p>
<p><strong>save() 方法</strong>通过传入的文档来替换已有文档。语法格式如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.save(</span><br><span class="line">   &lt;document&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure></p>
<p>以下实例中我们替换了 col_1 的文档数据：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">document = (&#123;</span><br><span class="line">    &quot;_id&quot;: &quot;1&quot;,</span><br><span class="line">    &quot;title&quot;: &quot;MongoDB save&quot;,</span><br><span class="line">    &quot;description&quot;: &quot;MongoDB 是一个 Nosql 数据库&quot;,</span><br><span class="line">    &quot;by&quot;: &quot;菜鸟&quot;,</span><br><span class="line">    &quot;url&quot;: &quot;http://www.runoob.com&quot;,</span><br><span class="line">    &quot;tags&quot;: [&quot;mongodb&quot;, &quot;database&quot;, &quot;NoSQL&quot;],</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">db.col_1.save(document)</span><br></pre></td></tr></table></figure></p>
<h2 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h2><p>find() 方法，它返回集合中所有文档。</p>
<p>findOne() 方法，它只返回一个文档。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find(query, projection)</span><br></pre></td></tr></table></figure></p>
<ul>
<li>query ：可选，使用查询操作符指定查询条件</li>
<li>projection ：可选，使用投影操作符指定返回的键。查询时返回文档中所有键值， 只需省略该参数即可（默认省略）。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">//格式化输出</span><br><span class="line">db.col_name.find().pretty()</span><br><span class="line">//查看集合中文档的个数</span><br><span class="line">db.col_name.find().count()</span><br><span class="line">//跳过指定数量的数据</span><br><span class="line">db.col_name.find().skip(2)</span><br><span class="line">//读取指定记录的条数</span><br><span class="line">db.col_name.find().limit(2)</span><br></pre></td></tr></table></figure>
<p>排序：<br>sort()方法可以通过参数指定排序的字段，并使用 1 和 -1 来指定排序的方式，其中 1 为升序排列，而-1是用于降序排列。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find().sort(&#123;key:1&#125;)</span><br></pre></td></tr></table></figure></p>
<p>sort()方法可以通过参数指定排序的字段，并使用 1 和 -1 来指定排序的方式，其中 1 为升序排列，而-1是用于降序排列。</p>
<h3 id="Where-语句"><a href="#Where-语句" class="headerlink" title="Where 语句"></a>Where 语句</h3><p>如果你想获取”col”集合中 “likes” 大于100，小于 200 的数据，你可以使用以下命令：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.col.find(&#123;likes : &#123;$lt :200, $gt : 100&#125;&#125;)</span><br><span class="line"></span><br><span class="line">// 类似于SQL语句：</span><br><span class="line">select * from col where likes&gt;100 AND  likes&lt;200;</span><br></pre></td></tr></table></figure></p>
<table>
<thead>
<tr>
<th style="text-align:center">条件操作符</th>
<th style="text-align:center">中文</th>
<th style="text-align:center">全英文</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">$gt</td>
<td style="text-align:center">大于</td>
<td style="text-align:center">greater than</td>
</tr>
<tr>
<td style="text-align:center">$gte</td>
<td style="text-align:center">大于等于</td>
<td style="text-align:center">greater than equal</td>
</tr>
<tr>
<td style="text-align:center">$lt</td>
<td style="text-align:center">小于</td>
<td style="text-align:center">less than</td>
</tr>
<tr>
<td style="text-align:center">$lte</td>
<td style="text-align:center">小于等于</td>
<td style="text-align:center">less than equal</td>
</tr>
<tr>
<td style="text-align:center">$ne</td>
<td style="text-align:center">不等于</td>
<td style="text-align:center">not equal</td>
</tr>
</tbody>
</table>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-27e67e57e7f046b4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/741/format/webp" alt=""></p>
<h3 id="type-操作符"><a href="#type-操作符" class="headerlink" title="$type 操作符"></a>$type 操作符</h3><p>用来检索集合中匹配的数据类型</p>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-4b259a703b51d8c8.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/743/format/webp" alt=""></p>
<p>如果想获取 “col” 集合中 title 为 String 的数据，你可以使用以下命令：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col.find(&#123;&quot;title&quot; : &#123;$type : 2&#125;&#125;)</span><br></pre></td></tr></table></figure></p>
<h3 id="AND-条件"><a href="#AND-条件" class="headerlink" title="AND 条件"></a>AND 条件</h3><p>find() 方法可以传入多个键(key)，每个键(key)以逗号隔开，语法格式如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find(&#123;key1:value1, key2:value2&#125;).pretty()</span><br><span class="line"></span><br><span class="line">// 类似于 SQL and 语句：</span><br><span class="line">SELECT * FROM col_name WHERE key1=&apos;value1&apos; AND key2=value2</span><br></pre></td></tr></table></figure></p>
<h3 id="OR-条件"><a href="#OR-条件" class="headerlink" title="OR 条件"></a>OR 条件</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find(&#123; $or: [&#123; &quot;by&quot;: &quot;菜鸟教程&quot; &#125;, &#123; &quot;title&quot;: &quot;MongoDB 教程&quot; &#125;] &#125;).pretty()</span><br><span class="line"></span><br><span class="line">// 类似于 SQL or 语句：</span><br><span class="line">SELECT * FROM col_name WHERE key1=value1 OR key2=value2</span><br></pre></td></tr></table></figure>
<h3 id="AND-和-OR-联合使用"><a href="#AND-和-OR-联合使用" class="headerlink" title="AND 和 OR 联合使用"></a>AND 和 OR 联合使用</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find(&#123;</span><br><span class="line">    &quot;likes&quot;: &#123;</span><br><span class="line">        $gt: 50</span><br><span class="line">    &#125;,</span><br><span class="line">    $or: [&#123;</span><br><span class="line">        &quot;by&quot;: &quot;菜鸟教程&quot;</span><br><span class="line">    &#125;, &#123;</span><br><span class="line">        &quot;title&quot;: &quot;MongoDB 教程&quot;</span><br><span class="line">    &#125;]</span><br><span class="line">&#125;).pretty()</span><br><span class="line"></span><br><span class="line">// 类似常规 SQL 语句：</span><br><span class="line">SELECT * FROM col_name where likes&gt;50 AND (by = &apos;菜鸟教程&apos; OR title = &apos;MongoDB 教程&apos;)</span><br></pre></td></tr></table></figure>
<h1 id="MongoDB-索引"><a href="#MongoDB-索引" class="headerlink" title="MongoDB - 索引"></a>MongoDB - 索引</h1><blockquote>
<p>注意：从 mongoDB 3.0 开始，ensureIndex 被废弃，今后都仅仅是 createIndex 的一个别名。</p>
</blockquote>
<p>索引通常能够极大的<strong><em>提高查询的效率</em></strong>，如果没有索引，MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。<br>这种扫描全集合的查询效率是非常低的，特别在处理大量的数据时，查询可以要花费几十秒甚至几分钟，这对网站的性能是非常致命的。</p>
<p>索引是特殊的数据结构，索引存储在一个易于遍历读取的数据集合中，索引是对数据库表中一列或多列的值进行排序的一种结构</p>
<h2 id="索引常用命令"><a href="#索引常用命令" class="headerlink" title="索引常用命令"></a>索引常用命令</h2><p>getIndexes 查看集合索引情况<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.getIndexes()</span><br></pre></td></tr></table></figure></p>
<p>hint 强制使用索引<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.find(&#123;age:&#123;$lt:30&#125;&#125;).hint(&#123;name:1, age:1&#125;).explain()</span><br></pre></td></tr></table></figure></p>
<p>删除索引(不会删除 _id 索引)<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.dropIndexes()</span><br><span class="line">//or</span><br><span class="line">db.col_name.dropIndex(&#123;firstname: 1&#125;)</span><br></pre></td></tr></table></figure></p>
<h2 id="createIndex-方法"><a href="#createIndex-方法" class="headerlink" title="createIndex() 方法"></a>createIndex() 方法</h2><p>MongoDB使用 createIndex() 方法来创建索引</p>
<p>key 为你要创建的索引字段，1为按升序创建索引，-1为按降序创建索引。<br>也可以设置使用多个字段创建索引（关系型数据库中称作复合索引）<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.createIndex(&#123;key:1&#125;)</span><br></pre></td></tr></table></figure></p>
<p>createIndex() 接收可选参数，可选参数列表如下：</p>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-a421f1c25b2a04ef.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/745/format/webp" alt=""></p>
<h3 id="id-索引"><a href="#id-索引" class="headerlink" title="_id 索引"></a>_id 索引</h3><p>对于每个插入的数据，都会自动生成一条唯一的 _id 字段，_id 索引是绝大多数集合默认建立的索引<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col_1.insert(&#123;x:10&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59658e56aaf42d1c98dd95a2&quot;), &quot;x&quot; : 10 &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.getIndexes()</span><br><span class="line">[</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;_id&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;_id_&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_1&quot;</span><br><span class="line">        &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure></p>
<p>字段解释：</p>
<ul>
<li>v 表示 version，在 Mongo3.2 之前的版本中，会存在 {v:0}（版本锁为0）的情况。在3.2之后的版本中，{v:0} 不再允许使用，这部分可以不去关注，因为 v 由系统自动管理</li>
<li>key 表示作为索引的键。1 或 -1表示排序模式，1为升序，1为降序</li>
<li>name 表示索引的名字，默认生成名称的规则是作为<code>索引的字段_排序模式</code></li>
<li>ns 表示 namespace 命名空间，由<code>数据库名称.集合名称</code>组成</li>
</ul>
<h3 id="单键索引"><a href="#单键索引" class="headerlink" title="单键索引"></a>单键索引</h3><p>最普通的索引，不会自动创建<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">// 对 x 字段创建升序索引</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.createIndex(&#123;x:1&#125;)</span><br><span class="line">&#123;</span><br><span class="line">        &quot;createdCollectionAutomatically&quot; : false,</span><br><span class="line">        &quot;numIndexesBefore&quot; : 1,</span><br><span class="line">        &quot;numIndexesAfter&quot; : 2,</span><br><span class="line">        &quot;ok&quot; : 1</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59658e56aaf42d1c98dd95a2&quot;), &quot;x&quot; : 10 &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.getIndexes()</span><br><span class="line">[</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;_id&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;_id_&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_1&quot;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;x&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;x_1&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_1&quot;</span><br><span class="line">        &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure></p>
<h3 id="多键索引"><a href="#多键索引" class="headerlink" title="多键索引"></a>多键索引</h3><p>单键索引的值为一个单一的值，多键索引的值有多个数据（如数组）<br>如果mongoDB中插入数组类型的多键数据，索引是<strong>自动建立</strong>的，无需刻意指定<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col_1.insert(&#123;z:[1,2,3,4,5]&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59658e56aaf42d1c98dd95a2&quot;), &quot;x&quot; : 10 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965923eaaf42d1c98dd95a3&quot;), &quot;y&quot; : 20 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59659828aaf42d1c98dd95a4&quot;), &quot;z&quot; : [ 1, 2, 3, 4, 5 ] &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_1.find(&#123;z:3&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59659828aaf42d1c98dd95a4&quot;), &quot;z&quot; : [ 1, 2, 3, 4, 5 ] &#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="复合索引"><a href="#复合索引" class="headerlink" title="复合索引"></a>复合索引</h3><p>同时对多个字段创建索引<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col_2.insert(&#123;x:10,y:20,z:30&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.col_2.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59659a57aaf42d1c98dd95a5&quot;), &quot;x&quot; : 10, &quot;y&quot; : 20, &quot;z&quot; : 30 &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_2.createIndex(&#123;x:1,y:1&#125;)</span><br><span class="line">&#123;</span><br><span class="line">        &quot;createdCollectionAutomatically&quot; : false,</span><br><span class="line">        &quot;numIndexesBefore&quot; : 1,</span><br><span class="line">        &quot;numIndexesAfter&quot; : 2,</span><br><span class="line">        &quot;ok&quot; : 1</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_2.getIndexes()</span><br><span class="line">[</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;_id&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;_id_&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_2&quot;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;x&quot; : 1,</span><br><span class="line">                        &quot;y&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;x_1_y_1&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_2&quot;</span><br><span class="line">        &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure></p>
<h3 id="过期索引"><a href="#过期索引" class="headerlink" title="过期索引"></a>过期索引</h3><p>又称 TTL（Time To Live，生存时间）索引，即在一段时间后会过期的索引（如登录信息、日志等）<br>过期后的索引会连同文档一起删除<br>expireAfterSeconds：指定一个以秒为单位的数值，设定集合的生存时间。</p>
<p>注意：</p>
<ul>
<li>存储在过期索引字段的值必须是指定的时间类型（必须是 ISODate 或 ISODate 数组，不能使用时间戳，否则不能被自动删除）</li>
<li>如果指定了 ISODate 数组，则按照最小的时间进行删除</li>
<li>过期索引不能是复合索引（不能指定两个过期时间）</li>
<li>删除时间存在些许误差（1 分钟左右）<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col_3.insert(&#123;x:new Date()&#125;)</span><br><span class="line">WriteResult(&#123; &quot;nInserted&quot; : 1 &#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.col_3.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;59659f3baaf42d1c98dd95a7&quot;), &quot;x&quot; : ISODate(&quot;2017-07-12T04:02:03.835Z&quot;) &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_3.createIndex(&#123;x:1&#125;,&#123;expireAfterSeconds:10&#125;)</span><br><span class="line">&#123;</span><br><span class="line">        &quot;createdCollectionAutomatically&quot; : false,</span><br><span class="line">        &quot;numIndexesBefore&quot; : 1,</span><br><span class="line">        &quot;numIndexesAfter&quot; : 2,</span><br><span class="line">        &quot;ok&quot; : 1</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_3.getIndexes()</span><br><span class="line">[</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;_id&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;_id_&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_3&quot;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">                &quot;v&quot; : 2,</span><br><span class="line">                &quot;key&quot; : &#123;</span><br><span class="line">                        &quot;x&quot; : 1</span><br><span class="line">                &#125;,</span><br><span class="line">                &quot;name&quot; : &quot;x_1&quot;,</span><br><span class="line">                &quot;ns&quot; : &quot;runoob.col_3&quot;,</span><br><span class="line">                &quot;expireAfterSeconds&quot; : 10</span><br><span class="line">        &#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">&gt; db.col_3.find()</span><br><span class="line">// 无返回</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="全文索引"><a href="#全文索引" class="headerlink" title="全文索引"></a>全文索引</h3><p>场景：全网站关键词搜索<br>key-value 中，key 此时为 <code>$**</code>（也可以是具体某 key），value 此时为一个固定的字符串（如 <code>text</code>）<br>全文索引相似度，与 sort 函数一起使用效果更好<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">db.col_7.find(&#123;</span><br><span class="line">    $text: &#123;</span><br><span class="line">        $search: &quot;aa bb&quot;</span><br><span class="line">    &#125;&#125;, &#123;</span><br><span class="line">    score: &#123;</span><br><span class="line">        $meta: &quot;textScore&quot;</span><br><span class="line">    &#125;</span><br><span class="line">	&#125;).sort(&#123;</span><br><span class="line">    score: &#123;</span><br><span class="line">        $meta: &quot;textScore&quot;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>注意：</p>
<ul>
<li>每个集合只能创建一个全文索引</li>
<li>MongoDB 从 2.4 版本开始支持全文检索，从 3.2 版本开始支持中文</li>
<li>（好像）只能对整个单词查询，不能对单词的截取部分查询</li>
<li>关键词之间的空格表示<code>或</code></li>
<li>关键词之前的 - 表示<code>非</code></li>
<li>关键词加引号表示<code>与</code> （需用 \ 转义）<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col_7.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa84aaf42d1c98dd95b0&quot;), &quot;title&quot; : &quot;aa bb cc&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa8faaf42d1c98dd95b1&quot;), &quot;title&quot; : &quot;abc def&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aedfaaf42d1c98dd95b2&quot;), &quot;title&quot; : &quot;aa bb&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.createIndex(&#123;&quot;title&quot;: &quot;text&quot;&#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.find(&#123;$text:&#123;$search:&quot;aa&quot;&#125;&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa84aaf42d1c98dd95b0&quot;), &quot;title&quot; : &quot;aa bb cc&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aedfaaf42d1c98dd95b2&quot;), &quot;title&quot; : &quot;aa bb&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.find(&#123;$text:&#123;$search:&quot;aa cc&quot;&#125;&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa84aaf42d1c98dd95b0&quot;), &quot;title&quot; : &quot;aa bb cc&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aedfaaf42d1c98dd95b2&quot;), &quot;title&quot; : &quot;aa bb&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.find(&#123;$text:&#123;$search:&quot;\&quot;aa\&quot; \&quot;cc\&quot;&quot;&#125;&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa84aaf42d1c98dd95b0&quot;), &quot;title&quot; : &quot;aa bb cc&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.find(&#123;$text:&#123;$search:&quot;aa bb&quot;&#125;&#125;,&#123;score:&#123;$meta:&quot;textScore&quot;&#125;&#125;).sort(&#123;score:&#123;$meta:&quot;textScore&quot;&#125;&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aedfaaf42d1c98dd95b2&quot;), &quot;title&quot; : &quot;aa bb&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot;, &quot;score&quot; : 1.5 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa84aaf42d1c98dd95b0&quot;), &quot;title&quot; : &quot;aa bb cc&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot;, &quot;score&quot; : 1.3333333333333333 &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&gt; db.col_7.dropIndexes()</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.createIndex(&#123;&quot;author&quot;: &quot;text&quot;&#125;))</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.find(&#123;$text:&#123;$search:&quot;小明&quot;&#125;&#125;)&#125;)</span><br><span class="line">&gt;</span><br><span class="line"></span><br><span class="line">&gt; db.col_7.find(&#123;$text:&#123;$search:&quot;白小明&quot;&#125;&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa84aaf42d1c98dd95b0&quot;), &quot;title&quot; : &quot;aa bb cc&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aa8faaf42d1c98dd95b1&quot;), &quot;title&quot; : &quot;abc def&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5965aedfaaf42d1c98dd95b2&quot;), &quot;title&quot; : &quot;aa bb&quot;, &quot;author&quot; : &quot;白小明&quot;, &quot;article&quot; : &quot;这是白小明的一篇文章，标题《aa bb cc》&quot; &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="地理位置索引"><a href="#地理位置索引" class="headerlink" title="地理位置索引"></a>地理位置索引</h3><p>查看最近的点<br>在此不介绍,想了解更多请<a href="https://docs.mongodb.com/manual/core/2dsphere/" target="_blank" rel="noopener">点击这里</a></p>
<h1 id="MongoDB-聚合"><a href="#MongoDB-聚合" class="headerlink" title="MongoDB - 聚合"></a>MongoDB - 聚合</h1><p>分组计算<br>MongoDB 中聚合主要用于处理数据(如平均值,求和等)，并返回计算后的数据结果。类似sql语句中的 count(*)。</p>
<h2 id="aggregate-方法"><a href="#aggregate-方法" class="headerlink" title="aggregate() 方法"></a>aggregate() 方法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_name.aggregate(AGGREGATE_OPERATION)</span><br></pre></td></tr></table></figure>
<p>下表展示了一些聚合的表达式:</p>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-8a6d608934b86d65.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/740/format/webp" alt=""></p>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><p><strong>计算每个作者所写的文章数</strong></p>
<p>在下面的例子中，我们通过字段by_user字段对数据进行分组，并计算by_user字段相同值的总和。</p>
<p>集合中的数据如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">        &quot;_id&quot; : ObjectId(&quot;5963b992a812aa05b9d2e765&quot;),</span><br><span class="line">        &quot;title&quot; : &quot;MongoDB Overview&quot;,</span><br><span class="line">        &quot;description&quot; : &quot;MongoDB is no sql database&quot;,</span><br><span class="line">        &quot;by_user&quot; : &quot;runoob.com&quot;,</span><br><span class="line">        &quot;url&quot; : &quot;http://www.runoob.com&quot;,</span><br><span class="line">        &quot;tags&quot; : [</span><br><span class="line">                &quot;mongodb&quot;,</span><br><span class="line">                &quot;database&quot;,</span><br><span class="line">                &quot;NoSQL&quot;</span><br><span class="line">        ],</span><br><span class="line">        &quot;likes&quot; : 100</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">        &quot;_id&quot; : ObjectId(&quot;5963b9aaa812aa05b9d2e766&quot;),</span><br><span class="line">        &quot;title&quot; : &quot;NoSQL Overview&quot;,</span><br><span class="line">        &quot;description&quot; : &quot;No sql database is very fast&quot;,</span><br><span class="line">        &quot;by_user&quot; : &quot;runoob.com&quot;,</span><br><span class="line">        &quot;url&quot; : &quot;http://www.runoob.com&quot;,</span><br><span class="line">        &quot;tags&quot; : [</span><br><span class="line">                &quot;mongodb&quot;,</span><br><span class="line">                &quot;database&quot;,</span><br><span class="line">                &quot;NoSQL&quot;</span><br><span class="line">        ],</span><br><span class="line">        &quot;likes&quot; : 10</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">        &quot;_id&quot; : ObjectId(&quot;5963b9bba812aa05b9d2e767&quot;),</span><br><span class="line">        &quot;title&quot; : &quot;Neo4j Overview&quot;,</span><br><span class="line">        &quot;description&quot; : &quot;Neo4j is no sql database&quot;,</span><br><span class="line">        &quot;by_user&quot; : &quot;Neo4j&quot;,</span><br><span class="line">        &quot;url&quot; : &quot;http://www.neo4j.com&quot;,</span><br><span class="line">        &quot;tags&quot; : [</span><br><span class="line">                &quot;neo4j&quot;,</span><br><span class="line">                &quot;database&quot;,</span><br><span class="line">                &quot;NoSQL&quot;</span><br><span class="line">        ],</span><br><span class="line">        &quot;likes&quot; : 750</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>使用aggregate()计算结果如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">db.col_1.aggregate([&#123;</span><br><span class="line">    $group: &#123;</span><br><span class="line">        _id: &quot;$by_user&quot;,</span><br><span class="line">        num_tutorial: &#123;</span><br><span class="line">            $sum: 1</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;])</span><br><span class="line"></span><br><span class="line">// 返回</span><br><span class="line">&#123; &quot;_id&quot; : &quot;Neo4j&quot;, &quot;num_tutorial&quot; : 1 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : &quot;runoob.com&quot;, &quot;num_tutorial&quot; : 2 &#125;</span><br><span class="line"></span><br><span class="line">// 以上实例类似sql语句</span><br><span class="line">select by_user, count(*) from col_1 group by by_user</span><br></pre></td></tr></table></figure></p>
<h2 id="聚合管道"><a href="#聚合管道" class="headerlink" title="聚合管道"></a>聚合管道</h2><p>管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。</p>
<p>MongoDB 的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。</p>
<p>表达式：处理输入文档并输出。表达式是无状态的，只能用于计算当前聚合管道的文档，不能处理其它的文档。</p>
<p>聚合管道常用的几个操作：</p>
<ul>
<li>$project：修改输入文档的结构。可以用来重命名、增加或删除域，也可以用于创建计算结果以及嵌套文档。</li>
<li>$match：用于过滤数据，只输出符合条件的文档。$match使用MongoDB的标准查询操作。</li>
<li>$limit：用来限制MongoDB聚合管道返回的文档数。</li>
<li>$skip：在聚合管道中跳过指定数量的文档，并返回余下的文档。</li>
<li>$unwind：将文档中的某一个数组类型字段拆分成多条，每条包含数组中的一个值。</li>
<li>$group：将集合中的文档分组，可用于统计结果。</li>
<li>$sort：将输入文档排序后输出。</li>
<li>$geoNear：输出接近某一地理位置的有序文档。</li>
</ul>
<h3 id="实例-1"><a href="#实例-1" class="headerlink" title="实例"></a>实例</h3><p><strong>$project 实例</strong></p>
<p>0 为不显示，1为显示，默认情况下 _id 字段是 1<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">db.articles.aggregate(&#123;</span><br><span class="line">    $project: &#123;</span><br><span class="line">        _id: 0,</span><br><span class="line">        title: 1,</span><br><span class="line">        by_user: 1,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"> // 返回</span><br><span class="line">&#123; &quot;title&quot; : &quot;MongoDB Overview&quot;, &quot;by_user&quot; : &quot;runoob.com&quot; &#125;</span><br><span class="line">&#123; &quot;title&quot; : &quot;NoSQL Overview&quot;, &quot;by_user&quot; : &quot;runoob.com&quot; &#125;</span><br><span class="line">&#123; &quot;title&quot; : &quot;Neo4j Overview&quot;, &quot;by_user&quot; : &quot;Neo4j&quot; &#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>$match 实例</strong></p>
<p>$match 用于获取分数大于70小于或等于90记录，然后将符合条件的记录送到下一阶段$group管道操作符进行处理。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.articles.aggregate([</span><br><span class="line">    &#123; $match: &#123; score: &#123; $gt: 70, $lte: 90 &#125; &#125; &#125;,</span><br><span class="line">    &#123; $group: &#123; _id: null, count: &#123; $sum: 1 &#125; &#125; &#125;</span><br><span class="line">]);</span><br><span class="line"></span><br><span class="line"> // 返回</span><br><span class="line">&#123; &quot;_id&quot; : null, &quot;count&quot; : 1 &#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>$skip 实例</strong></p>
<p>经过 $skip 管道操作符处理后，前2个文档被”过滤”掉。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col_1.aggregate(&#123; $skip: 2 &#125;);</span><br></pre></td></tr></table></figure></p>
<h1 id="MongoDB-复制"><a href="#MongoDB-复制" class="headerlink" title="MongoDB - 复制"></a>MongoDB - 复制</h1><p>MongoDB 复制（副本集）是==将数据同步在多个服务器==的过程。</p>
<p>复制提供了数据的冗余备份，并在多个服务器上存储数据副本，提高了数据的可用性， 并可以保证数据的安全性。</p>
<p>特点：</p>
<ul>
<li>保障数据的安全性</li>
<li>数据高可用性 (24*7)</li>
<li>灾难恢复，复制允许您从硬件故障和服务中断中恢复数据。</li>
<li>无需停机维护（如备份，重建索引，压缩）</li>
<li>分布式读取数据</li>
<li>N 个节点的集群</li>
<li>任何节点可作为主节点</li>
<li>所有写入操作都在主节点上</li>
<li>自动故障转移</li>
<li>自动恢复</li>
</ul>
<h2 id="复制原理"><a href="#复制原理" class="headerlink" title="复制原理"></a>复制原理</h2><p>mongodb 的复制至少需要两个节点。</p>
<ul>
<li>其中一个是==主节点==，负责处理客户端请求，</li>
<li>其余的都是==从节点==，负责复制主节点上的数据。</li>
</ul>
<p>mongodb各个节点常见的搭配方式为：一主一从、一主多从。</p>
<p>主节点记录在其上的所有操作oplog，从节点定期轮询主节点获取这些操作，然后对自己的数据副本执行这些操作，从而保证从节点的数据与主节点一致。</p>
<p><img src="//upload-images.jianshu.io/upload_images/5832745-e9d69c889fe53ec1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/500/format/webp" alt=""></p>
<h2 id="复制设置"><a href="#复制设置" class="headerlink" title="复制设置"></a>复制设置</h2><ol>
<li>关闭正在运行的MongoDB服务器。</li>
</ol>
<p>现在我们通过指定 –replSet 选项来启动mongoDB<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongod --port &quot;PORT&quot; --dbpath &quot;YOUR_DB_DATA_PATH&quot; --replSet &quot;REPLICA_SET_INSTANCE_NAME&quot;</span><br></pre></td></tr></table></figure></p>
<p>实例：</p>
<p>下面实例会启动一个名为rs0的MongoDB实例，其端口号为27017。</p>
<p>启动后打开命令提示框并连接上mongoDB服务。</p>
<p>在Mongo客户端使用命令rs.initiate()来启动一个新的副本集。</p>
<p>我们可以使用rs.conf()来查看副本集的配置</p>
<p>查看副本集状态使用 rs.status() 命令<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongod --port 27017 --dbpath &quot;D:\set up\mongodb\data&quot; --replSet rs0</span><br></pre></td></tr></table></figure></p>
<h2 id="副本集添加成员"><a href="#副本集添加成员" class="headerlink" title="副本集添加成员"></a>副本集添加成员</h2><p>添加副本集的成员，我们需要使用多条服务器来启动mongo服务。</p>
<p>进入Mongo客户端，并使用rs.add()方法来添加副本集的成员。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rs.add(HOST_NAME:PORT)</span><br></pre></td></tr></table></figure></p>
<p>实例：</p>
<p>假设你已经启动了一个名为 mongod1.net，端口号为27017的Mongo服务。</p>
<p>在客户端命令窗口使用rs.add() 命令将其添加到副本集中，命令如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rs.add(&quot;mongod1.net:27017&quot;)</span><br></pre></td></tr></table></figure></p>
<p>MongoDB 中你只能通过主节点将Mongo服务添加到副本集中， 判断当前运行的Mongo服务是否为主节点可以使用命令<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.isMaster()</span><br></pre></td></tr></table></figure></p>
<p>MongoDB的副本集与我们常见的主从有所不同，主从在主机宕机后所有服务将停止，而副本集在主机宕机后，副本会接管主节点成为主节点，不会出现宕机的情况。</p>
<h1 id="MongoDB-分片"><a href="#MongoDB-分片" class="headerlink" title="MongoDB - 分片"></a>MongoDB - 分片</h1><p>当MongoDB存储海量的数据时，==一台机器可能不足以存储数据==，也可能不足以提供可接受的读写吞吐量。这时，我们就可以通过在多台机器上分割数据，使得数据库系统能存储和处理更多的数据。</p>
<p>为什么使用分片？</p>
<ul>
<li>复制所有的写入操作到主节点</li>
<li>延迟的敏感数据会在主节点查询</li>
<li>单个副本集限制在12个节点</li>
<li>当请求量巨大时会出现内存不足。</li>
<li>本地磁盘不足</li>
<li>垂直扩展价格昂贵</li>
</ul>
<h2 id="分片集群结构"><a href="#分片集群结构" class="headerlink" title="分片集群结构"></a>分片集群结构</h2><p><img src="//upload-images.jianshu.io/upload_images/5832745-d9664d2b1c06bbae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600/format/webp" alt=""></p>
<p>三个主要组件：</p>
<ul>
<li>Shard: 用于存储实际的数据块，实际生产环境中一个shard server角色可由几台机器组个一个replica set承担，防止主机单点故障</li>
<li>Config Server: mongod实例，存储了整个 ClusterMetadata，其中包括 chunk信息。</li>
<li>Query Routers: 前端路由，客户端由此接入，且让整个集群看上去像单一数据库，前端应用可以透明使用。</li>
</ul>
<h1 id="MongoDB-监控"><a href="#MongoDB-监控" class="headerlink" title="MongoDB - 监控"></a>MongoDB - 监控</h1><p>监控可以了解 MongoDB 的==运行情况==及==性能==</p>
<p>MongoDB中提供了 mongostat 和 mongotop 两个命令来监控MongoDB的运行情况。</p>
<h2 id="mongostat"><a href="#mongostat" class="headerlink" title="mongostat"></a>mongostat</h2><p>它会间隔固定时间获取 mongodb 的当前运行状态，并输出。</p>
<p>如果你发现数据库突然变慢或者有其他问题的话，你第一手的操作就考虑采用 mongostat 来查看 mongo 的状态。</p>
<pre><code>mongostat
</code></pre><p><img src="//upload-images.jianshu.io/upload_images/5832745-56bf2bffa5a97ef4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/973/format/webp" alt=""></p>
<h2 id="mongotop"><a href="#mongotop" class="headerlink" title="mongotop"></a>mongotop</h2><p>mongotop用来跟踪MongoDB的实例，提供每个集合的统计数据。默认情况下，mongotop每一秒刷新一次。</p>
<pre><code>mongotop
</code></pre><p><img src="//upload-images.jianshu.io/upload_images/5832745-c423bb3678ba4d12.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/661/format/webp" alt=""></p>
<p>输出结果字段说明：</p>
<ul>
<li>ns：包含数据库命名空间，后者结合了数据库名称和集合。</li>
<li>db：包含数据库的名称。名为 . 的数据库针对全局锁定，而非特定数据库。</li>
<li>total：mongod花费的时间工作在这个命名空间提供总额。</li>
<li>read：提供了大量的时间，这mongod花费在执行读操作，在此命名空间。</li>
<li>write：提供这个命名空间进行写操作，这mongod花了大量的时间。</li>
</ul>
<p>等待的时间长度，以秒为单位，默认 1s</p>
<pre><code>mongotop 10
</code></pre><p>报告每个数据库的<strong>锁</strong>的使用</p>
<pre><code>mongotop --locks
</code></pre><h1 id="MongoDB-备份与恢复"><a href="#MongoDB-备份与恢复" class="headerlink" title="MongoDB - 备份与恢复"></a>MongoDB - 备份与恢复</h1><h2 id="mongodump"><a href="#mongodump" class="headerlink" title="mongodump"></a>mongodump</h2><p>在Mongodb中我们使用 <code>mongodump</code> 命令来备份MongoDB数据。</p>
<p>该命令可以导出所有数据到指定目录中。</p>
<p>mongodump命令可以通过参数指定导出的数据量级转存的服务器。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongodump -h dbhost -d dbname -o dbdirectory</span><br></pre></td></tr></table></figure></p>
<p>-h：MongDB所在服务器地址，例如：127.0.0.1，当然也可以指定端口号：127.0.0.1:27017<br>-d：需要备份的数据库实例，例如：test<br>-o：备份的数据存放位置，例如：c:\data\dump，当然该目录需要提前建立，在备份完成后，系统自动在dump目录下建立一个test目录，这个目录里面存放该数据库实例的备份数据。</p>
<h3 id="实例-2"><a href="#实例-2" class="headerlink" title="实例"></a>实例</h3><p>备份 mongodb_study 数据库中的所有集合到 E:\MongoDB\dump<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongodump -h 127.0.0.1 -d mongodb_study -o E:\MongoDB\dump</span><br></pre></td></tr></table></figure></p>
<p>不带任何参数，即在当前目录下备份所有数据库实例</p>
<pre><code>mongodump
</code></pre><p>备份所有MongoDB数据<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mongodump --host HOST_NAME --port PORT_NUMBER</span><br><span class="line"></span><br><span class="line">// 如</span><br><span class="line">mongodump --host w3cschool.cc --port 27017</span><br></pre></td></tr></table></figure></p>
<p>备份指定数据库的集合<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mongodump --collection COLLECTION_NAME --db DB_NAME</span><br><span class="line"></span><br><span class="line">// 如</span><br><span class="line">mongodump --collection mycol --db test</span><br></pre></td></tr></table></figure></p>
<h2 id="mongorestore"><a href="#mongorestore" class="headerlink" title="mongorestore"></a>mongorestore</h2><p>在Mongodb中我们使用 <code>mongorestore</code> 命令来恢复MongoDB数据。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongorestore -h &lt;hostname&gt;&lt;:port&gt; -d dbname &lt;path&gt;</span><br></pre></td></tr></table></figure></p>
<p>–host &lt;:port&gt;, -h &lt;:port&gt;：MongoDB所在服务器地址，默认为： localhost:27017<br>–db , -d ：需要恢复的数据库实例，例如：test，当然这个名称也可以和备份时候的不一样，比如test2<br>–drop：恢复的时候，先删除当前数据，然后恢复备份的数据。就是说，恢复后，备份后添加修改的数据都会被删除，慎用哦！<br>–path：mongorestore 最后的一个参数，设置备份数据所在位置，例如：c:\data\dump\test。你不能同时指定 <path></path> 和 –dir 选项，–dir也可以设置备份目录。<br>–dir：指定备份的目录，你不能同时指定 <path></path> 和 –dir 选项。</p>
<h3 id="实例-3"><a href="#实例-3" class="headerlink" title="实例"></a>实例</h3><p>恢复存放在 E:\MongoDB\dump 中的数据库 mongodb_study，恢复前后的数据库名不必相同<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongorestore -h localhost /db mongodb_study /dir E:\MongoDB\dump\mongodb_study</span><br></pre></td></tr></table></figure></p>
<p><br></p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果你觉得这篇文章对你有用，欢迎赞赏哦~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/wechatpay.png" alt="Felix 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/alipay.png" alt="Felix 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
	
	<div>
  
    <div>
    
        <div style="text-align: center;font-size: 13px;letter-spacing: 10px;user-select: none;margin-top: 50px;color: #bbb;">本文结束啦 <i class="fa fa-star"></i> 感谢您阅读</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" rel="tag"><i class="fa fa-tag"></i> MongoDB</a>
          
            <a href="/tags/NoSQL/" rel="tag"><i class="fa fa-tag"></i> NoSQL</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
               <div id="needsharebutton-postbottom">
                 <span class="btn" title="分享">
                    <i class="fa fa-share-alt" aria-hidden="true"></i>
                 </span>
               </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
			
			   <a href="/2018/11/09/手写mini版本的Spring/" rel="prev" title="手写mini版本的Spring">
			   <i class="fa fa-chevron-left"></i> 手写mini版本的Spring
			   
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
             
				<a href="/2018/11/06/Navicat-Premium-12-1-8-0安装与激活/" rel="next" title="Navicat Premium 12.1.8.0安装与激活">
				Navicat Premium 12.1.8.0安装与激活 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODUyNC8xNTA1Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/">
              <img class="site-author-image" itemprop="image"
                src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg"
                alt="Felix" />
				</a>
            
              <p class="site-author-name" itemprop="name">Felix</p>
              <p class="site-description motion-element" itemprop="description">周宇峰的博客</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">94</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">88</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/542869246" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/zyf542869246" target="_blank" title="Gitee"><i class="fa fa-fw fa-git"></i>Gitee</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://music.163.com/#/user/home?id=343583524" target="_blank" title="网易云音乐"><i class="fa fa-fw fa-music"></i>网易云音乐</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/yu-sui-58/activities" target="_blank" title="知乎"><i class="fa fa-fw fa-globe"></i>知乎</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://zblog.dawnings.top/" title="删库东😎" target="_blank">删库东😎</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ntssl.cn" title="ntssl.cn" target="_blank">ntssl.cn</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.imyzt.top/" title="imyzt" target="_blank">imyzt</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.charmsongo.cn/" title="charmsongo" target="_blank">charmsongo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.52share.online" title="HuiProgramer" target="_blank">HuiProgramer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://music.163.com/#/user/home?id=343583524" title="😆 网易云音乐 😆" target="_blank">😆 网易云音乐 😆</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhihu.com/people/yu-sui-58/activities" title="😤 知乎 😤" target="_blank">😤 知乎 😤</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/spring-boot.html" title="spring-boot 纯洁的微笑" target="_blank">spring-boot 纯洁的微笑</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" title="Python教程 廖雪峰" target="_blank">Python教程 廖雪峰</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="/about" title="关于此博客" target="_blank">关于此博客</a>
                  </li>
                
              </ul>
			  <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
            </div>
          

          
            
          
          <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-简介"><span class="nav-number">1.</span> <span class="nav-text">MongoDB - 简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-安装及运行"><span class="nav-number">2.</span> <span class="nav-text">MongoDB - 安装及运行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#mongoDB-主要特点"><span class="nav-number">3.</span> <span class="nav-text">mongoDB - 主要特点</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#mongoDB-工具"><span class="nav-number">4.</span> <span class="nav-text">mongoDB - 工具</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#mongoDB-三大重要概念"><span class="nav-number">5.</span> <span class="nav-text">mongoDB - 三大重要概念</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-database-数据库"><span class="nav-number">5.1.</span> <span class="nav-text">1. database 数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-collection-集合"><span class="nav-number">5.2.</span> <span class="nav-text">2. collection 集合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-document-文档"><span class="nav-number">5.3.</span> <span class="nav-text">3. document 文档</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-数据类型"><span class="nav-number">6.</span> <span class="nav-text">MongoDB - 数据类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-常见操作"><span class="nav-number">7.</span> <span class="nav-text">MongoDB - 常见操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#查看当前数据库"><span class="nav-number">7.1.</span> <span class="nav-text">查看当前数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看所有数据库"><span class="nav-number">7.2.</span> <span class="nav-text">查看所有数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#连接到指定的数据库"><span class="nav-number">7.3.</span> <span class="nav-text">连接到指定的数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看服务器状态"><span class="nav-number">7.4.</span> <span class="nav-text">查看服务器状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看数据库统计信息"><span class="nav-number">7.5.</span> <span class="nav-text">查看数据库统计信息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除数据库"><span class="nav-number">7.6.</span> <span class="nav-text">删除数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看数据库中所有集合"><span class="nav-number">7.7.</span> <span class="nav-text">查看数据库中所有集合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#清空集合"><span class="nav-number">7.8.</span> <span class="nav-text">清空集合</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-增删改查"><span class="nav-number">8.</span> <span class="nav-text">MongoDB - 增删改查</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#插入"><span class="nav-number">8.1.</span> <span class="nav-text">插入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除"><span class="nav-number">8.2.</span> <span class="nav-text">删除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更新"><span class="nav-number">8.3.</span> <span class="nav-text">更新</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询"><span class="nav-number">8.4.</span> <span class="nav-text">查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Where-语句"><span class="nav-number">8.4.1.</span> <span class="nav-text">Where 语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#type-操作符"><span class="nav-number">8.4.2.</span> <span class="nav-text">$type 操作符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AND-条件"><span class="nav-number">8.4.3.</span> <span class="nav-text">AND 条件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#OR-条件"><span class="nav-number">8.4.4.</span> <span class="nav-text">OR 条件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AND-和-OR-联合使用"><span class="nav-number">8.4.5.</span> <span class="nav-text">AND 和 OR 联合使用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-索引"><span class="nav-number">9.</span> <span class="nav-text">MongoDB - 索引</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#索引常用命令"><span class="nav-number">9.1.</span> <span class="nav-text">索引常用命令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#createIndex-方法"><span class="nav-number">9.2.</span> <span class="nav-text">createIndex() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#id-索引"><span class="nav-number">9.2.1.</span> <span class="nav-text">_id 索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单键索引"><span class="nav-number">9.2.2.</span> <span class="nav-text">单键索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多键索引"><span class="nav-number">9.2.3.</span> <span class="nav-text">多键索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复合索引"><span class="nav-number">9.2.4.</span> <span class="nav-text">复合索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#过期索引"><span class="nav-number">9.2.5.</span> <span class="nav-text">过期索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#全文索引"><span class="nav-number">9.2.6.</span> <span class="nav-text">全文索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#地理位置索引"><span class="nav-number">9.2.7.</span> <span class="nav-text">地理位置索引</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-聚合"><span class="nav-number">10.</span> <span class="nav-text">MongoDB - 聚合</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#aggregate-方法"><span class="nav-number">10.1.</span> <span class="nav-text">aggregate() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例"><span class="nav-number">10.1.1.</span> <span class="nav-text">实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#聚合管道"><span class="nav-number">10.2.</span> <span class="nav-text">聚合管道</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例-1"><span class="nav-number">10.2.1.</span> <span class="nav-text">实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-复制"><span class="nav-number">11.</span> <span class="nav-text">MongoDB - 复制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#复制原理"><span class="nav-number">11.1.</span> <span class="nav-text">复制原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#复制设置"><span class="nav-number">11.2.</span> <span class="nav-text">复制设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#副本集添加成员"><span class="nav-number">11.3.</span> <span class="nav-text">副本集添加成员</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-分片"><span class="nav-number">12.</span> <span class="nav-text">MongoDB - 分片</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#分片集群结构"><span class="nav-number">12.1.</span> <span class="nav-text">分片集群结构</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-监控"><span class="nav-number">13.</span> <span class="nav-text">MongoDB - 监控</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#mongostat"><span class="nav-number">13.1.</span> <span class="nav-text">mongostat</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#mongotop"><span class="nav-number">13.2.</span> <span class="nav-text">mongotop</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MongoDB-备份与恢复"><span class="nav-number">14.</span> <span class="nav-text">MongoDB - 备份与恢复</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#mongodump"><span class="nav-number">14.1.</span> <span class="nav-text">mongodump</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例-2"><span class="nav-number">14.1.1.</span> <span class="nav-text">实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#mongorestore"><span class="nav-number">14.2.</span> <span class="nav-text">mongorestore</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例-3"><span class="nav-number">14.2.1.</span> <span class="nav-text">实例</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-tint"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Felix</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">538k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:13</span>
  
  
  <div style="background-image:linear-gradient(90deg,#6dba82 0,#07b39b 15%,#1098ad 30%,#5073b8 44%,#a166ab 58%,#ef4e7b 72%,#f37055 86%,#f79533 100%);background-size:cover;-webkit-background-clip:text;-webkit-text-fill-color:transparent;user-select:none"><i>Tip: 本站电脑访问体验更佳耶&nbsp;<i class="fa fa-angellist" style="display:inline"></i></i></div>
  
</div>


<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>





-->



  <span>Hosted by <a href="https://pages.coding.me" >Coding Pages</a></span>



<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，加好友</div>
    </div>
  </div>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  
    <script type="text/javascript">
      window.livereOptions = {
        refer: '2018/11/06/MongoDB学习笔记（增删改查、聚合、索引、连接、备份与恢复、监控等）/'
      };
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text('Counter not initialized! See more at console err msg.');
              console.error('ATTENTION! LeanCloud counter has security bug, see here how to solve it: https://github.com/theme-next/hexo-leancloud-counter-security. \n But you also can use LeanCloud without security, by set \'security\' option to \'false\'.');
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz",
                'X-LC-Key': "xihAA2ETGTdekJFloguCmmgq",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Reddit,Delicious,StumbleUpon,Pinterest,Facebook,GooglePlus,Slashdot,Technorati,Posterous,Tumblr,GoogleBookmarks,Newsvine,Evernote,Friendfeed,Vkontakte,Odnoklassniki,Mailru";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Facebook,Tumblr,Friendfeed";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

  

  

  
  <div class="bg_content">
	<canvas id="canvas"></canvas>
	<canvas id="canvas1"></canvas>
	  <!-- html5-canvas-animation
	  <div class="canvas-wrap">
		<div id="canvas3" class="gradient"></div>
	</div>-->
  </div>
  
  
  
  <!-- 右上角github关注-->
  <div class="forkme">
	<!--<a href="https://github.com/542869246">
	<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://pd2tflnys.bkt.clouddn.com/img/blog/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
	</a>-->
	<a href="https://github.com/542869246" class="github-corner" aria-label="View source on GitHub">
	<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
	<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
	<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
	</svg>
	</a>
	<style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  </div>
  
  <!-- 音乐播放器-->
  <link rel="stylesheet" href="/dist/APlayer.min.css">
  <div id="aplayer"></div>
  <script type="text/javascript" src="/dist/APlayer.min.js"></script>
  <script type="text/javascript" src="/dist/music.js"></script>
 
   <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
 <!-- 页面点击汉字 -->
<script type="text/javascript" src="/js/src/hanzi.js"></script>
  
  <!-- 代码块复制功能 -->
<script type="text/javascript" src="/js/src/clipboard.min.js"></script>  
<script type="text/javascript" src="/js/src/clipboard-use.js"></script>
<!-- 流星雨-->
<!--<script type="text/javascript" src="/js/src/meteor-rain.js"></script>-->
<!-- 粒子效果-->
<script type="text/javascript" src="/js/src/dynamic_bg.js"></script>

<!-- html5-canvas-animation-->
<!-- Main library
<script src="/js/src/three.min.js"></script> -->
<!-- Helpers
<script src="/js/src/projector.js"></script>
<script src="/js/src/canvas-renderer.js"></script> -->
<!-- Visualitzation adjustments 
<script src="/js/src/3d-lines-animation.js"></script>-->
<!-- Animated background color 
<script src="/js/src/color.js"></script>-->



</body>
</html>
